#!/bin/sh
#
# Merge from trunk

PAGER=${DIFF_PAGER:=${PAGER:=less}}

usage()
{
	cat << EOT >&2
usage:
  $0 -a port...
  $0 -c M:N...
  $0 -r M[,N...]
EOT
	exit 1
}

# Ensure the repository is up-to-date before doing anything.
if ! svn update; then
	echo "*** Repository update failed!" >&2
	exit 1
fi

out=`svn status | grep -v '^?'`
if [ -n "${out}" ]; then
	echo "*** Repository has local modifications!" >&2
	exit 1
fi

_a=""
_c=""
_r=""

args=`getopt ac:r: $*`
if [ $? -ne 0 ]; then
	usage
fi
set -- $args

for i
do
	case "$i" in
		-a) _a=1; shift;;
		-c) _c="$2"; shift; shift;;
		-r) _r="$2"; shift; shift;;
		--) shift; break;;
	esac
done

if [ -z "${_a}${_c}${_r}" -o -n "${_c}" -a -n "${_r}" ]; then
	usage
fi

repo_root=`LC_ALL=C svn info | awk ' $1 == "URL:" { print $2 } '`
repo_trunk=`echo "${repo_root}" | sed -e 's|/branches/.*|/trunk|'`
repo_branch=`echo "${repo_root}" | sed -e 's|.*/branches/\([^/]*\).*|\1|'`

if [ -z "${repo_branch}" ]; then
	echo "*** MFT is intended to be run from a branch" >&2
	exit 1
fi

source=""
if [ -n "${_c}" ]; then
	svn merge -c "${_c}" ${repo_trunk} || exit 1
	source="changeset ${_c}"
elif [ -n "${_r}" ]; then
	svn merge -r "${_r}" ${repo_trunk} || exit 1
	source="revision ${_r}"
else
	for path; do
		echo "===> Merging ${path}..."
		last_chage=`LC_ALL=C svn info | awk ' $1 == "Last" && $2 == "Changed" && $3 == "Rev:" { print $4 }'`
		svn merge -r ${last_chage}:HEAD "${repo_trunk}/${path}" "${path}" || exit 1
	done
	source="revision ${last_chage}:HEAD for ${path}"
fi


# Now we have merged, look for Makefiles and cleannup PORTREVISION for ports
# with both the PORTVERSION and PORTREVISION changed.
for makefile in `svn status | awk ' $2 ~ /\/Makefile$/ { print $2 } '`; do
	svn diff "${makefile}" | grep -q '^+PORTVERSION'
	if [ $? -eq 0 ]; then
		# PORTVERSION changed. Ensure PORTREVISION is not set
		svn diff "${makefile}" | grep -q '^+PORTREVISION'
		if [ $? -eq 0 ]; then
			# Remove PORTREVISION
			mv "${makefile}" "${makefile}.orig" && cat "${makefile}.orig" | grep -v '^PORTREVISION' > "${makefile}" && rm "${makefile}.orig" || exit 1
		fi
	else
		# PORTVERSION is untouched. Ensure the new PORTREVISION is consistent.
		old_revision=`svn diff "${makefile}" | awk '$1 ~ /^-PORTREVISION/ { print $2 }'`
		new_revision=`svn diff "${makefile}" | awk '$1 ~ /^+PORTREVISION/ { print $2 }'`
		old_revision=${old_revision:=0}
		new_revision=${new_revision:=0}

		if [ $(( ${old_revision} + 1 )) -ne ${new_revision} ]; then
			mv "${makefile}" "${makefile}.orig" && cat "${makefile}.orig" | sed -e "s|^\\(PORTREVISION.*\\)${old_revision}|\\1$((${old_revision} + 1))|" > "${makefile}" && rm "${makefile}.orig" || exit 1
		fi
	fi
done


# Display changes and ask for committing.
if [ $? -eq 0 ]; then
	ans=""
	while [ "$ans" != "yes" -a "$ans" != "no" ]; do
		svn diff | ${PAGER}
		echo -n "Commit this? (yes/no) "
		read ans
	done
	if [ "$ans" = "yes" ]; then
		svn commit -m "(${repo_branch}) MFT from ${source}."
	fi
fi

